package com.stormrage.edu.ctrl;

import java.io.File;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.stormrage.edu.serv.acct.EntAcctServ;
import com.stormrage.edu.serv.learn.LeaBunchServ;
import com.stormrage.edu.serv.learn.LeaStudentCourseServ;
import com.stormrage.edu.serv.learn.LeaStudentServ;
import com.stormrage.edu.serv.student.StuAcctServ;
import com.stormrage.entity.ent.EntAcct;
import com.stormrage.entity.learn.LeaStudent;
import com.stormrage.entity.learn.rep.LeaBunchRep;
import com.stormrage.entity.learn.req.LeaBunchReq;
import com.stormrage.entity.learn.req.LeaStudentCourseReq;
import com.stormrage.entity.learn.req.LeaStudentReq;
import com.stormrage.entity.rep.ErrorRep;
import com.stormrage.entity.rep.JsonRep;
import com.stormrage.entity.rep.ListRep;
import com.stormrage.entity.shiro.ShiroAcct;
import com.stormrage.entity.student.StuInfo;
import com.stormrage.shiro.bind.CurrentUser;
import com.stormragetech.core.ctrl.BaseCtrl;
import com.stormragetech.core.entity.Page;

/**
 * @Title: LeaBunchCtrl.java
 * @Package com.stormrage.edu.ctrl
 * @Description: 班级 Controller
 * @author www.stormragetech.com
 * @date 2016年4月14日
 * @version V1.0
 */
@Controller
@RequestMapping("/bunch")
public class LeaBunchCtrl extends BaseCtrl {

	private static final Logger logger = LoggerFactory.getLogger(LeaApplyCtrl.class);

	@Value("#{constants['html.title']}")
	private String htmlTitle;

	@Value("#{constants['html.logo']}")
	private String htmlLogo;

	@Value("#{constants['path.root']}")
	private String rootPath;

	@Value("#{constants['path.excel']}")
	private String excelPath;

	@Autowired
	private EntAcctServ entAcctServ;

	@Autowired
	private LeaBunchServ leaBunchServ;

	@Autowired
	private LeaStudentServ leaStudentServ;

	@Autowired
	private LeaStudentCourseServ leaStudentCourseServ;

	@Autowired
	private StuAcctServ stuAcctServ;

	@RequestMapping(value = "/apply", method = RequestMethod.GET)
	public String apply(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 Apply 】-【 GET 】- 开始运行  ");

		try {

			// ------------------ 获取菜单 ------------------
			EntAcct acct = entAcctServ.queryById(Integer.valueOf(curr.getId()));

			LeaBunchReq req = LeaBunchReq.instance(null, null, acct.getEntId(), null,
					rootPath + excelPath + File.separator, null);
			List<LeaBunchRep> array = leaBunchServ.queryListForApply(req);

			model.addAttribute("user", curr);
			model.addAttribute("htmltitle", htmlTitle);
			model.addAttribute("htmllogo", htmlLogo);

			model.addAttribute("data", array);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 Apply 】-【 GET 】- 结束运行  ");
		return "bunch/apply";

	}

	@RequestMapping(value = "/{id}/apply", method = RequestMethod.GET)
	public String add(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 Apply 】-【 GET 】- 开始运行  ");

		try {

			model.addAttribute("user", curr);
			model.addAttribute("htmltitle", htmlTitle);
			model.addAttribute("htmllogo", htmlLogo);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 Apply 】-【 GET 】- 结束运行  ");
		return "bunch/add";

	}

	@RequestMapping(value = "/{id}/apply", method = RequestMethod.POST)
	public String add(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, StuInfo entity,
			RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 Apply 】-【 POST 】-【 STARTED 】");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			leaBunchServ.addStu(entity, id);
			errMsg = "提示信息：补充报名成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：补充报名失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/bunch/{id}/apply";
		}

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 Apply 】-【 POST 】-【 COMPLETED 】");
		return "redirect:/bunch/list";

	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 List 】-【 GET 】- 开始运行  ");

		try {

			// ------------------ 获取菜单 ------------------
			EntAcct acct = entAcctServ.queryById(Integer.valueOf(curr.getId()));

			LeaBunchReq req = LeaBunchReq.instance(null, null, acct.getEntId(), null,
					rootPath + excelPath + File.separator, 0);
			List<LeaBunchRep> array = leaBunchServ.queryList(req);

			model.addAttribute("user", curr);
			model.addAttribute("htmltitle", htmlTitle);
			model.addAttribute("htmllogo", htmlLogo);

			model.addAttribute("data", array);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 List 】-【 GET 】- 结束运行  ");
		return "bunch/list";

	}

	@RequestMapping(value = "/score", method = RequestMethod.GET)
	public String score(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 Score 】-【 GET 】- 开始运行  ");

		try {

			// ------------------ 获取菜单 ------------------
			EntAcct acct = entAcctServ.queryById(Integer.valueOf(curr.getId()));

			LeaBunchReq req = LeaBunchReq.instance(null, null, acct.getEntId(), null,
					rootPath + excelPath + File.separator, 0);
			List<LeaBunchRep> array = leaBunchServ.queryList(req);

			model.addAttribute("user", curr);
			model.addAttribute("htmltitle", htmlTitle);
			model.addAttribute("htmllogo", htmlLogo);

			model.addAttribute("data", array);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 Score 】-【 GET 】- 结束运行  ");
		return "bunch/score";

	}

	@RequestMapping(value = "/{id}/study")
	public String study(@CurrentUser ShiroAcct curr, LeaStudentReq req, Model model) {

		logger.debug(" 【 Controller 】-【 LeaBunchCtrl 】-【 Study 】-【 POST 】- 开始运行 ");

		try {

			// ------------------ Ctrl操作 ------------------
			String search = JSON.toJSONString(req);

			logger.debug(" 查询条件req变为search为 " + search);

			if (null != search && search.length() > 0)
				model.addAttribute("search", search);

			model.addAttribute("user", curr);
			model.addAttribute("htmltitle", htmlTitle);
			model.addAttribute("htmllogo", htmlLogo);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 LeaBunchCtrl 】-【 Study 】-【 GET 】- 结束运行 ");
		return "bunch/stu/study";
	}

	@RequestMapping(value = "/{id}/sajax", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String sajax(@RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, @PathVariable("id") Integer id,
			LeaStudentReq req) {

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 SAjax 】-【 POST 】-【 STARTED 】");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			req = LeaStudentReq.instance(req, id, 0, page);
			draw += 1;

			logger.debug(" 查询信息为 " + page.toString());

			ListRep entity = leaStudentServ.queryListForStudy(req);

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 SAjax 】-【 POST 】-【 COMPLETED 】");
		return json;

	}

	@RequestMapping(value = "/{id}/stu", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String stu(@PathVariable("id") Integer id, HttpServletResponse response) {

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 stu 】-【 GET 】-【 STARTED 】");

		try {

			response.setContentType("application/x-msdownload;charset=UTF-8");
			// response.setContentType("application/binary;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=student.xls");
			OutputStream os = response.getOutputStream();
			Workbook workbook = leaBunchServ.queryStudentExcel(id);
			workbook.write(os);
			os.flush();
			os.close();

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 stu 】-【 GET 】-【 COMPLETED 】");
		return null;

	}

	@RequestMapping(value = "/{aid}/{id}/pass", method = RequestMethod.GET)
	public String pass(@PathVariable("id") Integer id, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 stu 】-【 GET 】-【 STARTED 】");

		ErrorRep err = null;
		String errMsg = "";

		try {
			
			LeaStudent stu = leaStudentServ.queryById(id);
			stuAcctServ.editPass(stu.getAcctId());

			errMsg = "提示信息：初始化学员密码成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：初始化学员密码失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/bunch/{aid}/study";
		}

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 stu 】-【 GET 】-【 COMPLETED 】");
		return "redirect:/bunch/{aid}/study";

	}

	@RequestMapping(value = "/{id}/score")
	public String score(@CurrentUser ShiroAcct curr, LeaStudentReq req, Model model) {

		logger.debug(" 【 Controller 】-【 LeaBunchCtrl 】-【 Score 】-【 POST 】- 开始运行 ");

		try {

			// ------------------ Ctrl操作 ------------------
			String search = JSON.toJSONString(req);

			logger.debug(" 查询条件req变为search为 " + search);

			if (null != search && search.length() > 0)
				model.addAttribute("search", search);

			model.addAttribute("user", curr);
			model.addAttribute("htmltitle", htmlTitle);
			model.addAttribute("htmllogo", htmlLogo);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 LeaBunchCtrl 】-【 Score 】-【 GET 】- 结束运行 ");
		return "bunch/stu/score";
	}

	@RequestMapping(value = "/{id}/cajax", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String cajax(@RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, @PathVariable("id") Integer id,
			LeaStudentReq req) {

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 CAjax 】-【 POST 】-【 STARTED 】");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			req = LeaStudentReq.instance(req, id, 0, page);
			draw += 1;

			logger.debug(" 分页信息为 " + page.toString());

			ListRep entity = leaStudentServ.queryListForScore(req);

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 CAjax 】-【 POST 】-【 COMPLETED 】");
		return json;

	}

	@RequestMapping(value = "/{id}/oper", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String oper(@PathVariable("id") Integer id, HttpServletResponse response) {

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 oper 】-【 POST 】-【 STARTED 】");

		try {

			response.setContentType("application/x-msdownload;charset=UTF-8");
			// response.setContentType("application/binary;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=operscore.xls");
			OutputStream os = response.getOutputStream();
			Workbook workbook = leaBunchServ.queryOperExcel(id);
			workbook.write(os);
			os.flush();
			os.close();

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 oper 】-【 POST 】-【 COMPLETED 】");
		return null;

	}

	@RequestMapping(value = "/{id}/usua", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String usua(@PathVariable("id") Integer id, HttpServletResponse response) {

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 usua 】-【 POST 】-【 STARTED 】");

		try {

			response.setContentType("application/x-msdownload;charset=UTF-8");
			// response.setContentType("application/binary;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=usuascore.xls");
			OutputStream os = response.getOutputStream();
			Workbook workbook = leaBunchServ.queryUsuaExcel(id);
			workbook.write(os);
			os.flush();
			os.close();

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 usua 】-【 POST 】-【 COMPLETED 】");
		return null;

	}

	@RequestMapping(value = "/{aid}/{id}/info")
	public String info(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】-【 LeaBunchCtrl 】-【 Study 】-【 POST 】- 开始运行 ");

		try {

			// ------------------ Ctrl操作 ------------------

			model.addAttribute("user", curr);
			model.addAttribute("htmltitle", htmlTitle);
			model.addAttribute("htmllogo", htmlLogo);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 LeaBunchCtrl 】-【 Study 】-【 GET 】- 结束运行 ");
		return "bunch/stu/info";
	}

	@RequestMapping(value = "/{cid}/{id}/ajax", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String ajax(@RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, @PathVariable("id") Integer id) {

		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 ajax 】-【 POST 】-【 STARTED 】");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			LeaStudentCourseReq req = LeaStudentCourseReq.instance(id, page);
			draw += 1;

			logger.debug(" 查询信息为 " + page.toString());

			ListRep entity = leaStudentCourseServ.queryRepListByStuId(req);

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 LeaBunchCtrl 】- 【 ajax 】-【 POST 】-【 COMPLETED 】");
		return json;

	}

	@RequestMapping(value = "/{id}/upusua", method = RequestMethod.GET)
	public String upusua(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】- 【 LeaApplyCtrl 】- 【 upusua 】-【 GET 】- 开始运行  ");

		try {

			// ------------------ 获取菜单 ------------------

			model.addAttribute("user", curr);
			model.addAttribute("htmltitle", htmlTitle);
			model.addAttribute("htmllogo", htmlLogo);

			model.addAttribute("id", id);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】- 【 LeaApplyCtrl 】- 【 upusua 】-【 GET 】- 结束运行  ");
		return "bunch/usua/upload";

	}

	@RequestMapping(value = "/{id}/upusua", method = RequestMethod.POST)
	public String upusua(@CurrentUser ShiroAcct curr, @RequestParam(value = "file", required = true) MultipartFile file,
			RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】- 【 LeaApplyCtrl 】- 【 upusua 】-【 POST 】- 开始运行  ");

		ErrorRep err = null;
		String errMsg = "";

		if (null == file) {
			errMsg = "提示信息：上传平时成绩失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/bunch/{id}/upusua";
		}

		try {

			// ------------------ Ctrl操作 ------------------

			leaBunchServ.uploadUsua(file);

			errMsg = "提示信息：上传平时成绩成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：上传平时成绩失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/bunch/{id}/upusua";
		}

		logger.debug(" 【 Controller 】-【 LeaApplyCtrl 】-【 upusua 】-【 POST 】- 结束运行 ");
		return "redirect:/bunch/{id}/score";

	}

	@RequestMapping(value = "/{id}/upoper", method = RequestMethod.GET)
	public String upoper(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】- 【 LeaApplyCtrl 】- 【 upoper 】-【 GET 】- 开始运行  ");

		try {

			// ------------------ 获取菜单 ------------------

			model.addAttribute("user", curr);
			model.addAttribute("htmltitle", htmlTitle);
			model.addAttribute("htmllogo", htmlLogo);

			model.addAttribute("id", id);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】- 【 LeaApplyCtrl 】- 【 upoper 】-【 GET 】- 结束运行  ");
		return "bunch/oper/upload";

	}

	@RequestMapping(value = "/{id}/upoper", method = RequestMethod.POST)
	public String upoper(@CurrentUser ShiroAcct curr, @RequestParam(value = "file", required = true) MultipartFile file,
			RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】- 【 LeaApplyCtrl 】- 【 upoper 】-【 POST 】- 开始运行  ");

		ErrorRep err = null;
		String errMsg = "";

		if (null == file) {
			errMsg = "提示信息：上传实操成绩失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/bunch/{id}/upusua";
		}

		try {

			// ------------------ Ctrl操作 ------------------

			leaBunchServ.uploadOper(file);

			errMsg = "提示信息：上传实操成绩成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：上传实操成绩失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/bunch/{id}/upusua";
		}

		logger.debug(" 【 Controller 】-【 LeaApplyCtrl 】-【 upoper 】-【 POST 】- 结束运行 ");
		return "redirect:/bunch/{id}/score";

	}

}
